import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

// 白名单
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 设置页面title
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已经登录，则重定向到home页面
      // next({ path: '/' })
      next()
      // 关闭进度条
      NProgress.done()
    } else {
      // 判断用户是否已经登录并且
      const hasGetUserInfo = store.getters.userInfo
      const isLoad = store.state.permission.isLoad
      if (hasGetUserInfo && isLoad) {
        next()
      } else {
        store.dispatch('user/getInfo').then(res => {
          if (isLoad) {
            next()
          } else {
            store.dispatch('permission/generateRoutes', {})
              .then(accessRoutes => {
                router.addRoutes(accessRoutes)
                console.log(88888888888888)
                next({ ...to, replace: true })
              })
          }
        }).catch(error => {
          // 如果请求出现异常则重定向登录页，让用户重新登录后再跳转页面
          store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        })
      }
    }
    // 如果没有token且跳转页面不在白名单中则跳转登录页，让用户登录后再跳转相应的页面
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      Message.warning('请先登录!')
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})
